package com.strongbj.iot.devices.newlight.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.newlight.message.NewLightReaderMessage;
import com.strongbj.iot.devices.newlight.response.common.HandleTimeStamp;

import io.netty.channel.ChannelHandlerContext;

/**
 * 0x05，连续范围标签 LED 控制
 * @author lei_w
 *
 */
public class RangeTagLedControlResponseHandle implements IMessageHandle<NewLightReaderMessage, Object> {

	private static Logger logger = LogManager.getLogger(RangeTagLedControlResponseHandle.class.getName());
	
	@Override
	public boolean isHandle(NewLightReaderMessage t) {
		if (Integer.valueOf("5", 16).byteValue() == t.getType()) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, NewLightReaderMessage t) {
		String hostNumber = ByteUtil.byteArrToHexString(t.getAddress()); // reader 地址码
		String timeStamp = ByteUtil.byteArrToHexString(t.getTime()); // 时间戳
		
		short ctrlSuccNum = ByteUtil.byteArrToShort(t.getBody(), 0); // 控制成功个数
		String tagState = ByteUtil.byteToBitString(ByteUtil.subBytes(t.getBody(), 2, 1)[0]); // 标签其他状态	
		String powerState = tagState.substring(5, 8);
		String fbState = tagState.substring(3, 5);
		String fsState = tagState.substring(2, 3);
		String ledState = ByteUtil.byteToBitString(ByteUtil.subBytes(t.getBody(), 3, 1)[0]); // 标签LED状态
		String led1State = ledState.substring(6, 8);
		String led2State = ledState.substring(4, 6);
		String led3State = ledState.substring(2, 4);
		String led4State = ledState.substring(0, 2);
		short ctrlFailNum = ByteUtil.byteArrToShort(t.getBody(), 8); // 控制失败个数
		String ctrlFailShortAddress = ByteUtil.byteArrToHexString(t.getBody(), 10, ctrlFailNum * 2); // 控制失败段地址
		String log = "\r\n===================================================" +
				"\r\n收到连续范围标签LED控制返回报文：" + 
				"\r\nREADER地址码：" + hostNumber + 
				"\r\n控制成功个数：" + ctrlSuccNum + 
				"\r\n标签电量状态：  " + powerState + 
				"\r\n功能按键状态：  " + fbState + 
				"\r\n防撕状态：" + fsState +
				"\r\nLED1状态：" + led1State +
				"\r\nLED2状态：" + led2State +
				"\r\nLED3状态：" + led3State +
				"\r\nLED4状态：" + led4State +
				"\r\n 控制失败个数：" + ctrlFailNum + 
				"\r\n控制失败段地址：" + ctrlFailShortAddress + 
				"\r\n时间戳：" + HandleTimeStamp.handle(timeStamp);
		logger.info(log);
		return null;
	}

	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	}

}
